class EventsController < ApplicationController
  before_filter :set_nav_session
  before_filter :login_required, :except => [:index, :show, :all, :category]
  
  def index
    build_events(["events.end_at > now() and events.ref='dizhen.1kg.org'"])
  end
  
  def all
    build_events()
  end
  
  def category
    build_events(["events.category=? and events.ref='dizhen.1kg.org'", params[:cat].to_i])
  end
  
  def show
    @event = Event.find(params[:id])
    @comments = @event.comments
    @comment = EventComment.new
    @photos = @event.photos
  end
  
  def participations
    @participations = Participation.paginate(:page => params[:page] || 1,
                                             :conditions => "events.ref='dizhen.1kg.org'",
                                             :order => "participations.created_at desc", 
                                             :include => [:user, :event])
  end
  
  def new
    @event = Event.new
  end
  
  def create
    @event = Event.new(params[:event])
    @event.submitor = current_user
    # for dizhen.1kg.org
    @event.ref = 'dizhen.1kg.org'
    @event.save!
    flash[:notice] = "你刚刚发布了一个活动"
    redirect_back_or_default(event_path(@event))
  rescue ActiveRecord::RecordInvalid
    render :action => 'new'
  end
  
  def edit
    @event = Event.find(params[:id])
  end
  
  def update
    @event = Event.find(params[:id])
    @event.editable_by?(current_user) || access_denied
    @event.update_attributes!(params[:event])
    flash[:notice] = "您刚刚编辑了活动信息"
    redirect_back_or_default(event_path(@event))
  rescue ActiveRecord::RecordInvalid
    render :action => 'edit'
  end
  
  def destroy
    @event = Event.find(params[:id])
    @event.editable_by?(current_user) || access_denied
    @event.destroy
    flash[:notice] = "删除了#{@event.title}活动"
    redirect_to events_url
  end
  
  def new_pic
    @event_pic = EventPic.new
    @event = Event.find(params[:id])
  end
  
  def create_pic
    @event = Event.find(params[:id])
    @event_pic = EventPic.new(params[:event_pic])
    @event_pic.event = @event
    @event_pic.save!
    flash[:notice] = "您上传了活动图片"
    redirect_back_or_default(event_path(@event))
  end
  
  def join
    @participation = Participation.find(:first, :conditions => {:event_id => params[:id], :user_id => current_user.id})
    if @participation # each user can join the event once
      flash[:notice] = "您已经参加了这个活动"
      redirect_back_or_default(event_path(params[:id]))
    else
      @event = Event.find(params[:id])
      @participation = Participation.new
      @participation.event = @event
      @participation.user = current_user
      @participation.save!
      flash[:notice] = "您要参加这个活动"
      redirect_back_or_default(event_path(@event))
    end
  end
  
  # quit event
  def quit
    @event = Event.find(params[:id])
    @participation = Participation.find(:first, :conditions => {:user_id => current_user.id,
                                                                :event_id => @event.id})
    @participation.destroy
    redirect_back_or_default(event_path(@event))
  end
  
  # get school list, let user select which school is going to visit on 1kg more trip
  def choice_school
    @event = Event.find(params[:id])
    @provinces, @output = sort_by_province
  end
  
  def add_school
    @event = Event.find(params[:id])
    @school = School.find(params[:school_id])
    @event.school = @school
    @event.save!
    flash[:notice] = "#{@event.title}要去#{@school.id}"
    redirect_back_or_default(event_url(@event.id))
  end
    
  private
  def build_events(conditions = "1=1")
    @events = Event.paginate(:page => params[:page] || 1,
                             :conditions => conditions,
                             :order => "events.created_at desc",
                             :include => [:submitor, :school, :pic])
    @categories_count = Event.find_by_sql("select category, count(*) as count from events where ref='dizhen.1kg.org' group by category")
    @participations = Participation.recent_join
  end
  
  def sort_by_province
    areas = Area.find(2330,2186,2219,2175,2234,2187,2222)
    all_areas = []
    output = []
    areas.each do |area|
      #areas = province.all_children
      #unless areas.empty?
        schools = School.find(:all, 
                              :conditions => ["schools.is_hidden=? and schools.area_id=(?) and info_source='dizhen.1kg.org'", false, area], 
                              :joins => "left join users on schools.submitor_id = users.id",
                              :select => "schools.id, schools.title, schools.updated_at, schools.is_validate,
                                          schools.title, schools.submitor_id, users.login",
                              :order => "schools.area_id asc, schools.created_at desc")
        unless schools.empty?
          output[area.id] = schools
        end
      #end
    end
    areas.each do |area|
      unless output[area.id].blank?
        all_areas << area
      end
    end
    
    return all_areas, output
  end
  
  def set_nav_session
    session[:nav] = "events"
  end
end
